package com.bs.utils.spring;

import java.io.IOException;

import org.slf4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.DefaultResourceLoader;

import com.bs.utils.log.LogUtil;

/**********************************************************
 *
 * 文件名称：SpringUtil.java 
 * 摘    要：以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 *
 * 初始版本：1.0.0.0
 * 原 作 者：叶平平(yepp)
 * 完成日期：2014-12-5 下午8:14:51
 * 
 ************************************************************/

public  class SpringUtil implements ApplicationContextAware{
	
	private static Logger logger = LogUtil.get();
	
	private static ApplicationContext applicationContext;
	
	@SuppressWarnings("static-access")
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object getBean(Class requiredType){
		return applicationContext.getBean(requiredType);
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object getBean(String name, Class requiredType)throws BeansException {
		return applicationContext.getBean(name, requiredType);
	}

	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name)throws NoSuchBeanDefinitionException {
		return applicationContext.isSingleton(name);
	}

	@SuppressWarnings("rawtypes")
	public static Class getType(String name)throws NoSuchBeanDefinitionException {
		return applicationContext.getType(name);
	}

	public static String[] getAliases(String name)throws NoSuchBeanDefinitionException {
		return applicationContext.getAliases(name);
	}
	
	public static String getRootRealPath(){
		String rootRealPath="";
		try {
			rootRealPath =getApplicationContext().getResource("").getFile().getAbsolutePath();
		} catch (IOException e) {
			LogUtil.error(logger,"SpringUtil 获取系统根目录失败 ,{}",e);
		}
		return rootRealPath;
	}
	
	public static String getResourceRootRealPath(){
		String rootRealPath ="";
		try {
			rootRealPath=new DefaultResourceLoader().getResource("").getFile().getAbsolutePath();
		} catch (IOException e) {
			LogUtil.error(logger,"SpringUtil 获取资源根目录失败 ,{}",e);
		}
		return rootRealPath;
	}
	
	
	 
}
